package com.zahb.qadx.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.model.TrainAllBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.CurriculumDetailsActivity;
import com.zahb.qadx.ui.activity.TrainDetailsActivity;
import com.zahb.qadx.ui.activity.topic.DailyPracticeActivity;
import com.zahb.qadx.ui.activity.topic.TheTestActivity;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;

public class TrainTaskAdapter extends RecyclerView.Adapter<TrainTaskAdapter.TrainTaskViewHodler> {
    private Context mContext;

    private List<TrainAllBean.TaskListBean> dataBeanList;

    public TrainTaskAdapter(Context mContext, List<TrainAllBean.TaskListBean> dataBeanList) {
        this.mContext = mContext;
        this.dataBeanList = dataBeanList;
    }



    @NonNull
    @Override
    public TrainTaskViewHodler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new TrainTaskViewHodler(LayoutInflater.from(mContext).inflate(R.layout.item_list_traintask, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull TrainTaskViewHodler holder, int position) {
        int tasktype = dataBeanList.get(position).getTasktype();//tasktype=1在线课程  2 在线考试  3 在线练习  4  推荐课程
        String status = dataBeanList.get(position).getStatus(); //只要在线课程 才显示进度 1 未开始 2 已完成 3 进行中 4已过期
        int handleStatus = dataBeanList.get(position).getHandleStatus();//handleStatus=1未开始  2 进行中   3已过期


        if (tasktype == 1) {
            holder.tv_online.setText("在线课程");
            holder.tv_classname.setText(dataBeanList.get(position).getName());
            if (TextUtils.equals("1", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("未开始");
                holder.progress_bar.setVisibility(View.VISIBLE);
                holder.progress_bar.setProgress(0);
                holder.progress.setVisibility(View.VISIBLE);
                holder.progress.setText("0%");
            } else if (TextUtils.equals("2", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("已完成");
                holder.progress_bar.setVisibility(View.VISIBLE);
                holder.progress_bar.setProgress(100);
                holder.progress.setVisibility(View.VISIBLE);
                holder.progress.setText("100%");
            } else if (TextUtils.equals("3", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("进行中");
                holder.progress_bar.setVisibility(View.VISIBLE);
                holder.progress.setVisibility(View.VISIBLE);
                holder.progress_bar.setProgress((int) Double.parseDouble(dataBeanList.get(position).getAccounted()));
                holder.progress.setText((int) Double.parseDouble(dataBeanList.get(position).getAccounted()) + "%");
            } else if (TextUtils.equals("4", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("已过期");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
            }
            if (1 == handleStatus) {
                holder.btn_card_view.setClickable(false);
                holder.tv_btn_card_view.setText("未开始");
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
            } else if (2 == handleStatus) {
                holder.tv_btn_card_view.setText("去学习");
                holder.btn_card_view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tolearn(position);
                    }
                });
            } else if (3 == handleStatus) {
                holder.btn_card_view.setClickable(false);
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
                holder.tv_btn_card_view.setText("已过期");
            }


        } else if (tasktype == 2) {
            holder.tv_online.setText("在线考试");
            holder.tv_classname.setText(dataBeanList.get(position).getName());

            if (TextUtils.equals("1", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamStartTime()) + " 开始 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("未开始 0.00/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);

            } else if (TextUtils.equals("2", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamEndTime()) + " 截止 ");
                holder.tv_not_begin.setText("已完成 " + dataBeanList.get(position).getTaskHours() + "/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
                holder.tv_btn_card_view.setText("去考试");
            } else if (TextUtils.equals("3", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamEndTime()) + " 截止 ");
                holder.tv_not_begin.setText("未开始 0.00/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
                holder.tv_btn_card_view.setText("进行中");
            } else if (TextUtils.equals("4", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamEndTime()) + " 截止 ");
                holder.tv_not_begin.setText("未开始 0.00/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.tv_not_begin.setText("已过期");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
            }

            if (1 == handleStatus) {
                holder.tv_btn_card_view.setText("未开始");
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamStartTime()) + " 开始 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("未开始 0.00/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
                holder.btn_card_view.setClickable(false);
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
            } else if (2 == handleStatus) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamEndTime()) + " 截止 ");
                holder.tv_btn_card_view.setText("去考试");
                holder.btn_card_view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toexam(position);
                    }
                });
            } else if (3 == handleStatus) {

                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getExamEndTime()) + " 截止 ");
                holder.btn_card_view.setClickable(false);
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
                holder.tv_btn_card_view.setText("已过期");
            }


        } else if (tasktype == 3) {
            holder.tv_online.setText("在线练习");
            holder.tv_classname.setText(dataBeanList.get(position).getName());
            if (TextUtils.equals("1", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getStartTime()) + " 开始 " + dataBeanList.get(position).getTaskHours() + "学时");
                holder.tv_not_begin.setText("未开始 0.00/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);

            } else if (TextUtils.equals("2", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 ");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
                holder.tv_not_begin.setText("已完成 " + dataBeanList.get(position).getTaskHours() + "/" + dataBeanList.get(position).getTaskHours() + " 学时");

            } else if (TextUtils.equals("3", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 ");
                holder.tv_not_begin.setText("未开始 0.00/" + dataBeanList.get(position).getTaskHours() + " 学时");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
            } else if (TextUtils.equals("4", status)) {
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 ");
                holder.tv_not_begin.setText("已过期");
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
            }
            if (1 == handleStatus) {
                holder.tv_btn_card_view.setText("未开始");
                holder.btn_card_view.setClickable(false);
                holder.progress_bar.setVisibility(View.GONE);
                holder.progress.setVisibility(View.GONE);
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
            } else if (2 == handleStatus) {
                holder.tv_btn_card_view.setText("去练习");
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 ");
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#1677FF"));
                holder.btn_card_view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        topractice(position);
                    }
                });
            } else if (3 == handleStatus) {
                holder.btn_card_view.setClickable(false);
                holder.tv_time.setText(TrainDetailsActivity.splitTime(dataBeanList.get(position).getEndTime()) + " 截止 ");
                holder.btn_card_view.setCardBackgroundColor(Color.parseColor("#dcdcdc"));
                holder.tv_btn_card_view.setText("已过期");
            }

        }


    }

    @Override
    public int getItemCount() {
        return dataBeanList != null ? dataBeanList.size() : 0;
    }

    static class TrainTaskViewHodler extends RecyclerView.ViewHolder {

        private CardView btn_card_view;
        private TextView tv_online, tv_classname, tv_time, tv_btn_card_view, tv_not_begin, progress;
        private ProgressBar progress_bar;

        public TrainTaskViewHodler(@NonNull View itemView) {
            super(itemView);

            btn_card_view = itemView.findViewById(R.id.btn_card_view);//点击按钮
            tv_online = itemView.findViewById(R.id.tv_online_class);
            tv_classname = itemView.findViewById(R.id.tv_classname);//课程名称
            tv_time = itemView.findViewById(R.id.tv_start_time);//截止时间
            tv_btn_card_view = itemView.findViewById(R.id.tv_btn_card_view);
            tv_not_begin = itemView.findViewById(R.id.tv_not_begin);//未开始
            progress_bar = itemView.findViewById(R.id.progress_bar_new);//进度条
            progress = itemView.findViewById(R.id.progress_new);//进度
        }
    }

    private static final Gson mGson = new Gson();

    private void tolearn(int position) {
        if (BaseApplication.getContext().getDataLogin() == null) {
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("courseId", dataBeanList.get(position).getTaskId());
        params.put("courseSnapshotId", dataBeanList.get(position).getTaskVersionId());
        params.put("relationshipId", dataBeanList.get(position).getClassUserTaskOnly());
        params.put("relationshipType", 2);
        params.put("rootOrgId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        params.put("userId", BaseApplication.getContext().getDataLogin().getUser().getId());

        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        RetrofitService.getNetService()
                .toLearn(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        String courseUserId = response.getData();
                        Log.e("data====", "data" + courseUserId);
                        Curriculum curriculum = new Curriculum(Integer.parseInt(dataBeanList.get(position).getTaskId()), dataBeanList.get(position).getName(), "",
                                dataBeanList.get(position).getImg(), dataBeanList.get(position).getTaskVersionId(), courseUserId);
                        curriculum.setRelationshipId(dataBeanList.get(position).getClassUserTaskOnly());
                        curriculum.setRelationshipType("2");

                        CurriculumDetailsActivity.actionStart(mContext, curriculum, CurriculumDetailsActivity.TYPE_FROM_TASK);

                    }
                }, throwable -> {
                    throwable.printStackTrace();

                });
    }

    private void topractice(int position) {
        Map<String, Object> params = new HashMap<>();
        params.put("endTime", dataBeanList.get(position).getEndTime());
        params.put("practiceId", dataBeanList.get(position).getTaskId());
        params.put("relationshipId", dataBeanList.get(position).getClassUserTaskOnly());
        params.put("relationshipType", 2);
        params.put("startTime", dataBeanList.get(position).getStartTime());
        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        RetrofitService.getNetService()
                .topractice(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        try {
                            String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                            String url = WebViewHelper.getBaseUrl() + "practice?trainType=1&fromType=1&classUserTaskOnly=" + dataBeanList.get(position).getClassUserTaskOnly() + "&token=" + token + "&version=" + getVersionCode(mContext) + "&practiceId=" + dataBeanList.get(position).getTaskId();
                            Log.e("MyWebViewActivity", "url: " + url);
                            String json1 = tojson(1, dataBeanList.get(position).getTasktype(), dataBeanList.get(position).getClassUserTaskOnly());

                            //拼接json对象
                            //原生去练习
                            // TODO: 2021/5/12 暂时关闭 MyWebViewActivity.actionStart(mContext, url, "", 1, json1);
                            SharedPreferences settingss = mContext.getSharedPreferences("tryToSwitch", 0);
                            int isAmazing = settingss.getInt("tryToSwitch", 0);
                            if (isAmazing == 2) {
                                Intent intent = new Intent(mContext, DailyPracticeActivity.class);
                                intent.putExtra("practiceId", dataBeanList.get(position).getTaskId());
                                intent.putExtra("path", 2);
                                intent.putExtra("json", json1);
                                startActivity(intent);
                            } else {
                                MyWebViewActivity.actionStart(mContext, url, "", 1, json1);
                            }

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }, throwable -> {
                    throwable.printStackTrace();

                });
    }

    //封装的请求json
    public static String tojson(int actorType, int objType, String relationshipId) {

        Map<String, Object> params = new HashMap<>();
        Map<String, Object> actor = new HashMap<>();
        actor.put("actorId", BaseApplication.getContext().getDataLogin().getUser().getId());
        actor.put("actorType", actorType);
        Map<String, Object> extensions = new HashMap<>();
        extensions.put("organizationId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        actor.put("extensions", extensions);
        params.put("actor", actor);

        Map<String, Object> objectInfo = new HashMap<>();
        objectInfo.put("objType", objType);
        params.put("objectInfo", objectInfo);

        Map<String, Object> context = new HashMap<>();
        Map<String, Object> extensions1 = new HashMap<>();
        extensions1.put("relationshipId", relationshipId);
        context.put("extensions", extensions1);
        params.put("context", context);

        Log.e("ttttttt", mGson.toJson(params));
        return mGson.toJson(params);

    }

    private void toexam(int position) {
        if (BaseApplication.getContext().getDataLogin() == null) {
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("endTime", dataBeanList.get(position).getEndTime());
        params.put("examId", dataBeanList.get(position).getTaskId());
        params.put("relationshipId", dataBeanList.get(position).getClassUserTaskOnly());
        params.put("relationshipType", 2);
        params.put("startTime", dataBeanList.get(position).getStartTime());
        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        RetrofitService.getNetService()
                .toexam(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        try {
                            String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
                            String url = WebViewHelper.getBaseUrl() + "exam/examInfo?trainType=1&fromType=1&classUserTaskOnly=" + dataBeanList.get(position).getClassUserTaskOnly() + "&token=" + token + "&version=" + getVersionCode(mContext) + "&sourceId=" + dataBeanList.get(position).getTaskId();
                            Log.e("MyWebViewActivity", "url: " + url);

                            // TODO: 2021/5/12  去考试
                            SharedPreferences settingss = mContext.getSharedPreferences("tryToSwitch", 0);
                            int isAmazing = settingss.getInt("tryToSwitch", 0);
                            if (isAmazing == 2) {
                                Intent intent = new Intent(mContext, TheTestActivity.class);
                                intent.putExtra("examId", dataBeanList.get(position).getTaskId());
                                intent.putExtra("relationshipId", dataBeanList.get(position).getClassUserTaskOnly());
                                startActivity(intent);
                            } else {
                                MyWebViewActivity.actionStart(mContext, url, "", 1);
                            }


                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }, throwable -> {
                    throwable.printStackTrace();

                });
    }

    /**
     * 获取App版本号
     *
     * @param context 上下文
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return 1;
        }
    }
}
